﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using Dycox.ComponentModel;

namespace Dycox
{
    public static class EnumHelpers
    {
        public static string GetText(this Enum value, string seperator = " | ")
        {
            Type type = value.GetType();

            if (Enum.IsDefined(type, value))
                return GetText(type, value);

            if (type.GetCustomAttributes(typeof(FlagsAttribute), false).Length > 0)
            {
                Array array = Enum.GetValues(type);
                List<string> list = new List<string>(array.Length);
                object zero = Enum.ToObject(type, 0);
                foreach (Enum v in array)
                {
                    if (!zero.Equals(v) && value.HasFlag(v))
                        list.Add(GetText(type, v));
                }

                if (list.Count > 0)
                    return string.Join(seperator, list);
            }
            
                return value.ToString();
        }

        private static string GetText(Type type, object value)
        {
            string name = Enum.GetName(type, value);
            DescriptionAttribute da = (DescriptionAttribute)Attribute.GetCustomAttribute(
                type.GetField(name), typeof(DescriptionAttribute));

            if (da != null)
                name = da.Description;

            return name;
        }

        public static bool TryParse(Type enumType, string s, out object value)
        {
            foreach (var fld in enumType.GetFields())
            {

                if (string.Equals(fld.Name, s, StringComparison.InvariantCultureIgnoreCase))
                {
                    value = fld.GetValue(null);
                    return true;
                }

                DescriptionAttribute da = (DescriptionAttribute)Attribute.GetCustomAttribute(
                    fld, typeof(DescriptionAttribute));

                if (da != null && string.Equals(da.Description, s, StringComparison.InvariantCultureIgnoreCase))
                {
                    value = fld.GetValue(null);
                    return true;
                }
            }

            value = null;
            return false;
        }

        public static EnumListItem CreateListItem(this Enum value)
        {
            return new EnumListItem(value);
        }
    }
}
